package com.xingdata.jjxc.activity.viewdata;

import jar.MessageManager;
import jar.model.RequestEntity;
import jar.tools.InstructionSet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.xingdata.jjxc.App;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.activity.IssueActivity;
import com.xingdata.jjxc.adapter.FindAllAdapter;
import com.xingdata.jjxc.enty.FindAllEntity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.http.HttpUtil;
import com.xingdata.jjxc.utils.Consumer;
import com.xingdata.jjxc.utils.ImageUtils;
import com.xingdata.jjxc.utils.MessageCode;
import com.xingdata.jjxc.utils.SystemInfo;
import com.xingdata.jjxc.views.MyListView;
import com.xingdata.jjxc.views.MyListView.OnLoadMoreListener;
import com.xingdata.jjxc.views.MyListView.OnRefreshListener;

/**
 * 发现页面
 * 
 * @author Administrator
 * 
 */
public class FindAllData implements OnClickListener, OnLoadMoreListener, OnRefreshListener {
	private String TAG = "FindAllData";
	private Context mcontext;
	private View tabview;
	private MyListView listview;
	private FindAllAdapter findAllAdapter;
	private List<FindAllEntity> findAllEntlist = new ArrayList<FindAllEntity>();
	private List<String> idsList = new ArrayList<String>();
	private Button serch_button;
	private Button goBack;
	private Handler mHandler;
	private int startNumber = 0;
	private int inLenght = 10;
	private ArrayList<ImageView> imageViews = new ArrayList<ImageView>();
	private Consumer consumer = new Consumer();
	// private Spinner typeSpinner;
	private ArrayList<String> typeList = new ArrayList<String>();
	private PopupWindow typeWindow = null;
	private LinearLayout titlelayout;

	public FindAllData(View tabContentView, Context mcontext, Bundle savedInstanceState) {
		this.mcontext = mcontext;
		this.tabview = tabContentView;
		initHandle();
		initView();
		doPost_getDiscoverList(startNumber);
	}

	private void initView() {
		String types[] = mcontext.getResources().getStringArray(R.array.findAll_type);
		if (typeList.size() != 0) {
			typeList.clear();
		}
		for (String s : types) {
			typeList.add(s);
		}
		tabview.findViewById(R.id.findtype_layout).setOnClickListener(this);

		listview = (MyListView) tabview.findViewById(R.id.findallmain_lv);
		listview.setCanLoadMore(true);
		listview.setCanRefresh(true);
		// 向前刷新
		listview.setOnRefreshListener(this);
		// 加载更多
		listview.setOnLoadListener(this);
		serch_button = (Button) tabview.findViewById(R.id.serch_button);
		goBack = (Button) tabview.findViewById(R.id.goBack);
		serch_button.setOnClickListener(this);
		goBack.setOnClickListener(this);
		findAllAdapter = new FindAllAdapter(tabview, mcontext, findAllEntlist, imageViews, mHandler, consumer);
		// LinearLayout mLodingLayout = (LinearLayout) View.inflate(mcontext,
		// R.layout.listview_footer, null);
		// listview.addFooterView(mLodingLayout);
		tabview.findViewById(R.id.load_more).setOnClickListener(this);
		listview.setAdapter(findAllAdapter);
		titlelayout = (LinearLayout) tabview.findViewById(R.id.findtype_layout);
	}

	private void initHandle() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case MessageCode.MessageCode_RefreshControl:
					findAllAdapter.notifyDataSetChanged();
					break;

				default:
					break;
				}
			}
		};

	}

	/**
	 * 请求发现列表
	 */
	private void doPost_getDiscoverList(final int start) {
		String dis_type = titlelayout.getTag().toString();
		final boolean isReafresh;
		if (start == 0) {
			isReafresh = true;
		} else {
			isReafresh = false;
		}
		Log.i(TAG, "start : " + start);
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("beginnum", start + "");
		paramsMap.put("endnum", start + inLenght + "");
		paramsMap.put("dis_type", dis_type);
		HttpUtil.getInstance(mcontext).Post(App.ZZD_REQUEST_GETDISCOVERLIST, paramsMap, new HttpResponseListener() {
			@Override
			public void onSuccess(RespEntity respEntity) {
				listview.onLoadMoreComplete();
				listview.onRefreshComplete();
				if (start == 0) {
					findAllEntlist.clear();
					idsList.clear();
				}

				if (respEntity.getResult() != null) {

					boolean isChange = false;
					ArrayList<FindAllEntity> arrayList = (ArrayList<FindAllEntity>) JSON.parseArray(
							respEntity.getResult(), FindAllEntity.class);

					for (FindAllEntity entity : arrayList) {
						if (!idsList.contains(entity.getDis_id())) {
							isChange = true;
							if (isReafresh) {
								// 如果是刷新就插在最前面 很蛋疼的功能.....
								findAllEntlist.add(0, entity);
							} else {
								findAllEntlist.add(entity);
							}
						}
					}

					if (isChange) {
						findAllAdapter.notifyDataSetChanged();
						// 本地过滤重复数据 服务器没做校验
						for (FindAllEntity entity : findAllEntlist) {
							idsList.add(entity.getDis_id());
						}
					}
					startNumber = findAllEntlist.size();
				}
			}

			@Override
			public void onLoading(int vurrent) {

			}

			@Override
			public void onFailure(String result) {

			}

		});

	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		// 抓拍按钮
		case R.id.serch_button:
			MessageManager.send(Integer.parseInt(SystemInfo.getHUD_System_Port()), new RequestEntity("",
					InstructionSet.INSTRUCTION_AUTH_CAPTURE_TO_HUD + ""));
			break;

		case R.id.goBack:
			intent = new Intent(mcontext, IssueActivity.class);
			mcontext.startActivity(intent);
			break;

		case R.id.load_more:
			doPost_getDiscoverList(startNumber);
			break;

		case R.id.findtype_layout:
			// showPOP();
			break;
		case R.id.find_all:
			Query(v);
			break;
		case R.id.find_help:
			Query(v);
			break;
		case R.id.find_video:
			Query(v);
			break;
		}

	}

	private void Query(View v) {
		titlelayout.setTag(v.getTag());
		startNumber = 0;
		doPost_getDiscoverList(startNumber);
		// 动态设置标题
		((TextView) titlelayout.findViewWithTag("find_title")).setText(((TextView) v).getText());
		closePOP();
	}

	private void closePOP() {
		// TODO Auto-generated method stub
		if (typeWindow != null && typeWindow.isShowing()) {
			typeWindow.dismiss();
		}
	}

	public void onDestroy() {
		consumer.cancleAll();
		for (ImageView imageView : imageViews) {
			ImageUtils.releaseImageViewResouce(imageView);
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		doPost_getDiscoverList(0);
	}

	@Override
	public void onLoadMore() {
		doPost_getDiscoverList(startNumber);
	}

	/**
	 * 现实POP
	 * 
	 * @param marker
	 * @return
	 */
	private boolean showPOP() {
		if (typeWindow == null) {
			typeWindow = new PopupWindow(mcontext);
			final View pop_view = View.inflate(mcontext, R.layout.popupwindow_findtype, null);
			typeWindow.setContentView(pop_view);
			typeWindow.setWidth(LayoutParams.MATCH_PARENT);
			typeWindow.setHeight(LayoutParams.WRAP_CONTENT);
			typeWindow.setFocusable(true);
			typeWindow.setOutsideTouchable(false);
			typeWindow.setAnimationStyle(R.style.popup_fade_anim);
			// 20%黑
			ColorDrawable dw = new ColorDrawable(0x33000000);
			typeWindow.setBackgroundDrawable(dw);
			pop_view.setOnTouchListener(new OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					int height = pop_view.findViewById(R.id.pop_layout).getTop();
					int y = (int) event.getY();
					if (event.getAction() == MotionEvent.ACTION_UP) {
						if (y < height) {
							typeWindow.dismiss();
						}
					}
					return true;
				}
			});
			pop_view.findViewById(R.id.find_help).setOnClickListener(this);
			pop_view.findViewById(R.id.find_video).setOnClickListener(this);
			pop_view.findViewById(R.id.find_all).setOnClickListener(this);
		}

		int[] location = new int[2];
		titlelayout.getLocationOnScreen(location);
		typeWindow.showAsDropDown(titlelayout);
		// typeWindow.showAtLocation(
		// tabview.findViewById(R.id.type), Gravity.BOTTOM
		// | Gravity.CENTER_HORIZONTAL, 0, 0);

		return false;

	}

}
